package com.scilvet.reportcomposer.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

import au.com.bytecode.opencsv.CSVWriter;

import com.scilvet.reportcomposer.exception.FileException;
import com.scilvet.reportcomposer.report.Line;
import com.scilvet.reportcomposer.report.Report;
import com.scilvet.reportcomposer.report.TitleLine;

public class CSVReportWriter implements ReportWriter {
	
	public static final String EXTENSION = ".csv";
	
	private Logger logger = Logger.getLogger(CSVReportWriter.class); 

	@Override
	public void writeReport(Report report, File outputFile) throws FileException {
		
		if (report == null || outputFile == null) {
			throw new IllegalArgumentException("writeReport called with null parameter");
		}
		
		logger.info(report.printValues());
		
		try {
			CSVWriter writer = new CSVWriter(new FileWriter(outputFile), ';');
			
			String[] header = {"Line", "Description", "Value"};
			writer.writeNext(header);
			
			String[] emptyLine = {" ", " ", " "};

			for (Line line : report) {
				
				if (line instanceof TitleLine) {
					writer.writeNext(emptyLine);
				}
				writer.writeNext(line.lineArray());
			}
			
			writer.close();
			
		} catch (IOException e) {
			logger.error(e.getMessage());
			throw new FileException("Error while writing report data to file " + outputFile.getAbsolutePath(), e);
		}
	}

}
